package gogen

import (
	_ "embed"
	"fmt"
	"strings"

	"github.com/zeromicro/go-zero/tools/goctl/api/spec"
	"github.com/zeromicro/go-zero/tools/goctl/config"
	"github.com/zeromicro/go-zero/tools/goctl/util/format"
)

const (
	configFile = "config"

	jwtTemplate = ` struct {
		AccessSecret string
		AccessExpire int64
	}
`
	jwtTransTemplate = ` struct {
		Secret     string
		PrevSecret string
	}
`
)

//go:embed config.tpl
var configTemplate string

//go:embed confconfig.tpl
var pkgConfigTemplate string

func genConfig(dir string, cfg *config.Config, api *spec.ApiSpec) error {
	filename, err := format.FileNamingFormat(cfg.NamingFormat, configFile)
	if err != nil {
		return err
	}

	authNames := getAuths(api)
	var auths []string
	for _, item := range authNames {
		auths = append(auths, fmt.Sprintf("%s %s", item, jwtTemplate))
	}

	if err = genPkgConfig(dir); err != nil {
		return err
	}

	return genFile(fileGenConfig{
		dir:             dir,
		subdir:          configDir,
		filename:        filename + ".go",
		templateName:    "configTemplate",
		category:        category,
		templateFile:    configTemplateFile,
		builtinTemplate: configTemplate,
		data: map[string]string{
			"auth":     strings.Join(auths, "\n"),
			"jwtTrans": "",
		},
	})
}

func genPkgConfig(dir string) error {
	return genFile(fileGenConfig{
		dir:             dir,
		subdir:          "pkg/conf",
		filename:        "config.go",
		templateName:    "pkgConfigTemplate",
		category:        "",
		templateFile:    "confconfig.tpl",
		builtinTemplate: pkgConfigTemplate,
		data:            map[string]string{},
	})
}
